<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-09
 * Time: 14:07
 */

namespace app\api\controller;


use app\service\CardsService;
use app\service\CardVisitedService;
use app\service\MsgService;
use app\service\UserService;
use think\Session;

class Cardvisited extends Base
{
    //添加访问者
    public function add_visited(){
        $input = input('');
        if(!isset($input['card_id']) || empty($input['card_id'])){
            $this->ajax(202,'参数不完整');
        }else{
            $card_info = CardsService::S()->findCard(['a.id'=>['eq',$input['card_id']]]);
            if(empty($card_info)){
                $this->ajax(202,'名片信息不存在');
            }else if($card_info['user_id']== $this->uid){
                $this->ajax(202,'浏览自己不需添加访问者');
            }
        }

        $save_data = [
            'card_id' => $input['card_id'],
            'visited_id' => $this->uid,
            'visited_time' => time(),
        ];
        $where = [
            'card_id' => ['eq',$input['card_id']],
            'visited_id' => ['eq',$this->uid]
        ];
        $user_info = CardVisitedService::S()->findVisited($where,'id,last_time');

        if($user_info){

            if(\session('?cardVisited_' . $this->uid . '_' . $input['card_id'])){
                $user = UserService::S()->findUser(['id'=>['eq',$this->uid]],'nickname');
                $data['first']='客户查看了您的名片';
                $data['nickname']=$user['nickname'];
                $data['visited_time']=date('Y年m月d日 H:i:s');
                $data['remark']='请留意客户联系您';
                $res = MsgService::S()->sendTemp(MsgService::$tempType_NEW_CARDVISITED,$this->mall_id,$card_info['user_id'],$data);
            }
            $this->ajax(202,'访问者信息已存在');
        }else{
            session('cardVisited_'. $this->uid . '_' . $input['card_id'],1,3600);
            $user = UserService::S()->findUser(['id'=>['eq',$this->uid]],'nickname');
            $data['first']='客户查看了您的名片';
            $data['nickname']=$user['nickname'];
            $data['visited_time']=date('Y年m月d日 H:i:s');
            $data['remark']='请留意客户联系您';
//            $re = MsgService::S()->sendTemp(MsgService::$tempType_NEW_USER,$this->mall_id,$card_info['user_id'],$data);
            $re = MsgService::S()->sendTemp(MsgService::$tempType_NEW_CARDVISITED,$this->mall_id,$card_info['user_id'],$data);
            $res = CardVisitedService::S()->addVisited($save_data);
        }
        if($res){
            $this->ajax(200,'添加成功',$res);
        }else{
            $this->ajax(202,'添加失败');
        }

    }

}